import md5 from 'js-md5'
import {
	getToken
} from '@/utils/token.js'
const upVideo = {
	file: null, //文件对象
	size: 0, //分片大小 kb
	progressBar: 0, //进度条 num%
	underWayFn: null, //进度条改变触发函数
	upOverFn: null, //上传完成触发函数
	t: null, //定时器
	fileType: null, //文件类型（100-图片，101-视频，102-文件）
	fileCode: null, //文件路径code
	acVideoData:'',
	// 初始化函数
	init({
		fileObj, //文件对象
		fileCode,
		size = 20, //分片大小 默认2  单位m
		fileType = 101, //文件类型（100-图片，101-视频，102-文件）
		underWayFn = function() {}, //进度条改变触发函数
		upOverFn = function() {}, //上传完成触发函数
	}) {
		this.file = fileObj.tempFile;
		this.acFile = fileObj
		this.size = size * 1024 * 1024;
		this.underWayFn = underWayFn;
		this.upOverFn = upOverFn;
		this.fileTy = fileType;
		this.code = fileCode;
		uni.showLoading({
			title:'上传中'
		})
		// 判断是否是满足条件的视频对象 满足条件调用this.upbegin()处理
		this.upbegin();
	},
	// 上传文件
	async upbegin() {
		let videoTime = await this.videoLong(); //视频播放时间
		// 视频分片
		let start = 0,
			end = 0,
			chunkArr = [],
			size = this.size;
		let file = this.file;

		function chuli() {
			end += size;
			var blob = file.slice(start, end);
			start += size;
			if (blob.size) {
				chunkArr.push(blob);
				chuli(file);
			} else {
				return chunkArr
			}
		}
		chuli();
		//预请求接口 然后this.inTurnto(chunkArr); 分片请求
		// 分片请求主体
		this.inTurnto(chunkArr);
	},
	// 缓慢增长到目标进度条
	changeProgressBar(num,res) {
		if(res.data.includes('?') == false){
			this.acVideoData = res.data
		}
		clearInterval(this.t)
		this.t = setInterval(() => {
			if (this.progressBar == num) {
				clearInterval(this.t)
				//上传完成
				if (this.progressBar === 100) {
					this.upOverFn(this.acVideoData); //通知上传完成
					this.clearUpVideo(); //格式化重置
					uni.hideLoading();
					uni.showToast({
						title:'上传成功',
						icon:'none'
					})
				}
			} else {
				this.progressBar++;
				this.underWayFn(this.progressBar); //改变进度条通知
			}
		}, 50);
	},

	// 多个视频一一请求
	inTurnto(chunkArr) {
		const chunkAllNum = chunkArr.length; //片段总数量
		let count = 0; //完成个数
		chunkArr.forEach((item, index) => {
			let arr = this.acFile.name.split('.')
			let params = {
				file: item,
				suffix: arr[arr.length - 1],
				shardIndex: index + 1,
				shardSize: item.size,
				shardTotal: chunkAllNum,
				size: this.acFile.size,
				key: md5(this.acFile.name + this.acFile.size + this.acFile.type + this.acFile.duration),
				fileType: this.fileTy,
				filePathCode: this.code
			}
			uni.uploadFile({
				url: 'https://job.ydylmold.cn/file/upload',
				filePath: this.acFile.tempFilePath,
				name: 'file',
				formData: {
					...params,
					fileParaName: 'file'
				},
				header: {
					'token': getToken('token')
				},
				success: (res) => {
					count++;
					this.changeProgressBar(parseInt(count / chunkAllNum * 100),res); //改变进度
				},
				fail: (err) => {
					uni.hideLoading()
					uni.showToast({
						title:'上传出错',
						icon:'none'
					})
				}
			})
		
		})
	},


	// 获取视频总时长
	videoLong() {
		return new Promise((resolve) => {
			var url = URL.createObjectURL(this.file);
			var audioElement = new Audio(url);
			audioElement.addEventListener("loadedmetadata", function() {
				var hour = parseInt((audioElement.duration) / 3600);
				if (hour < 10) {
					hour = "0" + hour;
				}
				var minute = parseInt((audioElement.duration % 3600) / 60);
				if (minute < 10) {
					minute = "0" + minute;
				}
				var second = Math.ceil(audioElement.duration % 60);
				if (second < 10) {
					second = "0" + second;
				}
				resolve(hour + ":" + minute + ":" + second)
			});
		})
	},
	// 重置
	clearUpVideo() {
		this.file = null;
		this.size = 0;
		this.progressBar = 0;
		this.underWayFn = null;
		this.upOverFn = null;
		this.t = null;
		this.fileTy = null;
	},
}


export default upVideo
